package util;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLParser {

	
	/**
	 * {@link XMLParser} 实例
	 */
	private static final XMLParser instance = new XMLParser();

	private Map<String, Relation> map = new HashMap<String, Relation>();
	
	/**
	 * 私有化构造
	 */
	private XMLParser() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document document;
		try {
			db = dbf.newDocumentBuilder();
			document = db.parse("res\\relations.xml");
			init(document.getChildNodes());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void init(NodeList nodes) {
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			NodeList ns = node.getChildNodes();
			for (int j = 0; j < ns.getLength(); j++) {
				Node item = ns.item(j);
				
				NodeList ns2 = item.getChildNodes();
				
				Relation c = createContact(ns2);
				
				map.put(c.orienter, c);
			}
		}
	}

	private Relation createContact(NodeList ns2) {
		String orienter = ns2.item(0).getTextContent();
		String henchmans = ns2.item(1).getTextContent();

		Relation r = new Relation(orienter);
		String[] ss = henchmans.split(",");
		for (String s : ss) {
			r.henchmans.add(s);
		}
		return r;
	}

	/**
	 * 获取该对象唯一实例
	 * @return
	 */
	public static final XMLParser getInstance() {
		return instance;
	}

	public static void main(String[] args) {
		XMLParser ins = XMLParser.getInstance();
//		System.out.println(ins.contains("person.name"));
		System.out.println(ins.contains("person"));
		
		for (Relation c : ins.map.values()) {
			System.out.println(c);
		}
		
	}
	
	/**
	 * 是否包含表
	 * @param table
	 * @return
	 */
	public boolean contains(String table) {
		return map.containsKey(table);
	}
	
	public Set<String> getRelations() {
		return map.keySet();
	}
	
	public Relation getRelation(String key) {
		return map.get(key);
	}
	
	public static class Relation {
		public final String orienter;
		public final Set<String> henchmans = new HashSet<String>();
		
		public Relation(String orienter) {
			this.orienter = orienter;
		}
		
		@Override
		public String toString() {
			StringBuilder sb = new StringBuilder();

			sb.append("orienter = ");
			sb.append(orienter);
			sb.append("\rhenchmans = ");
			for (String s : henchmans) {
				sb.append("\t" + s);
			}
			return sb.toString();
		}
		
	}
}
